//app.js
var util = require('./utils/utils.js');
var api = require('./api.js');
App({
  is_on_launch: true,
  BOTTOM_DISTANCE:0,//iponeX底部需要抬高的距离
  onLaunch: function () {
    let that = this;
    
    //获取手机型号
    wx.getSystemInfo({
      success(res) {
        let sysInfo = res;
        wx.setStorageSync('systemInfo', sysInfo);
        const model = res.model;
        const modelInclude = ["iPhone X", 'iPhone XR', "iPhone XS", "iPhone XS MAX","iPhone 11","iPhone 11 PRO"];
        var flag = false;//是否X以上机型
        for (let i = 0; i < modelInclude.length;i ++){
          //模糊判断是否是modelInclude 中的机型,因为真机上测试显示的model机型信息比较长无法一一精确匹配
          if (model.indexOf(modelInclude[i]) != -1){
            flag = true
          }
        }
        if (flag) {
         that.BOTTOM_DISTANCE = 50;
        }
      }
    })
    // this.getStoreData();
    //  this.getCatList();
    /**
     * login统一放到allow页面
     */
    // var token = wx.getStorageSync("token");
    // console.log('token:' + token);
    // if (!token){
    //   this.login();
    // }
  },

  getStoreData: function () {
    var page = this;
    this.request({
      url: api.default.store,
      data: {
        id: 1
      },
      success: function (res) {
        if (res.code == 200) {
          wx.setStorageSync("storeaddress", res.data.storeaddress);
          wx.setStorageSync("store_name", res.data.storename);
          wx.setStorageSync("storeinfo", res.data.storeinfo);
          wx.setStorageSync("contact_tel", res.data.storetelephone);
          wx.setStorageSync("storeower", res.data.storeower);
        }
      },
      complete: function () {
        page.login();
      }
    });
  },

  getCatList: function () {
    this.request({
      url: api.default.cat_list,
      data: {
        limit: 15
      },
      success: function (res) {
        if (res.code == 200) {
          var cat_list = res.data.rows || [];
          wx.setStorageSync("cat_list", cat_list);
        }
      }
    });
  },
  login: function (hasCallback,response,callback,callbackParam) {
    let self = this;
    var pages = getCurrentPages();
    var page = pages[(pages.length - 1)];
    wx.showLoading();
    wx.login({
      success: function (loginres) {
        if (loginres.code) {
          var code = loginres.code;
            wx.request({
              url: api.passport.login,
              method: "get",
              data: {
                code: code,
              },
              success: function (res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                  let data = res.data.data;
                  const tokenStr = data.tokenHead + data.token
                  wx.setStorageSync('loginToken', tokenStr)
                  wx.setStorageSync('token', data.token);
                  wx.setStorageSync("hasMemberInfo", data.hasMemberInfo);
                  wx.setStorageSync("sessionKey", data.sessionKey);
                  if (response && hasCallback){
                    if (!data.hasMemberInfo){
                      self.userAnthBind(response, callback);
                    }else{
                      callback(callbackParam);
                    }
                  };
                  if( !response && callback && callbackParam){
                    callback(callbackParam);
                  };
                  self.checkUserIditity();
                } else {
                  wx.showToast({
                    title: res.data.message || res.message,
                    icon:"none"
                  });
                }
              },
              fail:function(res){
                console.log("failed")
              }
            });
          //   }
          // });
        } else {
          //console.log(res);
        }
      }
    });
    
  },
  userAnthBind(res,callback){ //用户点击授权登录
    let page = this;
    var sessionKey = wx.getStorageSync("sessionKey");
    console.log(sessionKey);
    this.request({
      url: api.user.saveUserInfo,
      method:"post",
      data: {
        "encryptedData": res.detail.encryptedData,
        "iv": res.detail.iv,
        "rawData": res.detail.rawData,
        "sessionKey": sessionKey,
        "signature": res.detail.signature
      },
      success: function (response) {
        if (response.code == 200) {
         // page.getMemberInfo();
          //wx.setStorageSync('user_info', res.detail.rawData);
          wx.setStorageSync('hasMemberInfo', true);
          
          callback();
        }else{
            wx.showToast({
              title: response.message,
              icon:'none',
              duration:1000
            })
          }
      }
    });
  },
  request: function (object) {
    let self = this;
    var token = wx.getStorageSync("token");
    let loginToken = wx.getStorageSync('loginToken');
    //console.log('token:' + token);
    let deviceInfo = wx.getStorageSync("systemInfo");
    if (token) {
      if (!object.data)
        object.data = {};
      // object.data.access_token = access_token;
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: object.url,
      header: object.header || {
       // 'content-type': 'application/x-www-form-urlencoded',
        'content-type': 'application/json',
        'version': '1.0.0',
        'device': deviceInfo.system,
        'system': 'wx',
        'token': token,
        'Authorization':loginToken, // 让每个请求携带自定义token 请根据实际情况自行修改
        },
      data: Object.assign({}, object.data),
      method: object.method || "GET",
      dataType: object.dataType || "json",
      success: function (res) {
        // res.data.code === 100101 ||
        if (res.data.code === 401) {
          //token过期，清空本地跟token有关系的缓存
          wx.removeStorageSync('loginToken');
          wx.removeStorageSync('token');
          wx.removeStorageSync('hasMemberInfo');
          wx.removeStorageSync('sessionKey');
          // console.log("登录过期，需要重新登录"); //object.url
          // wx.showToast({
          //   title: '微信登陆过期，请重新登陆',
          //   icon: 'none'
          // })
          // wx.navigateTo({
          //   url: '/pages/allow/allow',
          // });
          console.log(object);
          wx.hideLoading();
          // self.login(null,null,self.request,object);
        } else {
          if (object.success){
            wx.hideLoading();
            object.success(res.data);
          }
        }
      },
      fail: function (res) {
        wx.hideLoading();
        var app = getApp();
        if (app.is_on_launch) {
          app.is_on_launch = false;
          wx.showModal({
            title: "网络请求出错",
            content: res.errMsg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                if (object.fail)
                  object.fail(res);
              }
            }
          });
        } else {
          console.log("shfbdjkjfhbjsk")
          wx.showToast({
            title: res.errMsg || res.message,
            image: "/images/icon-warning.png",
          });
          if (object.fail)
            object.fail(res);
        }
      },
      complete: function (res) {
        console.log(object.url);
        console.log(res);
        // wx.hideLoading();
        // if (res.data.code==200){
          
        // }else{
        //   setTimeout(()=>{
        //     wx.hideLoading();
        //   },2000)
        // }
        if (object.complete){
          object.complete(res);
        }
      }
    });
  },
  checkUserIditity(callback){//查询用户是否为经销商
    let page = this;
    page.request({
      url: api.user.checkUserId,
      success:function(res){
        if (res.code == 200) {
          console.log(res.data);
          let data = res.data;
          if(data.distributor){
            wx.setStorageSync('user_sharecode',data.invitationCode);//用户自己的分享码
          }else{
            wx.removeStorageSync('user_sharecode');
          }
          if(callback){
            callback(data);
          }
        }
      }
    })
  },
    //绑定经销商
    bindSalesInfo(share_code) {
      let page = this;
      if(!share_code) return;
      page.request({
        url: api.user.bindSalesInfo + share_code,
        success: function (res) {
          if (res.code == 200) {
            console.log(res);
          }
        }
      })
    },
  saveFormId: function (form_id) {
    this.request({
      url: api.user.save_form_id,
      data: {
        form_id: form_id,
      }
    });
  },

  loginBindParent: function (object) {
    var token = wx.getStorageSync("token");
    if (token == '') {
      return true;
    }
    getApp().bindParent(object);
  },
  bindParent: function (object) {
    if (object.parent_id == "undefined" || object.parent_id == 0)
      return;
    console.log("Try To Bind Parent With User Id:" + object.parent_id);
    var user_info = wx.getStorageSync("user_info");
    var share_setting = wx.getStorageSync("share_setting");
    if (share_setting.level > 0) {
      var parent_id = object.parent_id;
      if (parent_id != 0) {
        getApp().request({
          url: api.share.bind_parent,
          data: { parent_id: object.parent_id },
          success: function (res) {
            if (res.code == 200) {
              user_info.parent = res.data
              wx.setStorageSync('user_info', user_info);
            }
          }
        });
      }
    }
  },

  /**
   * 分享送优惠券
   * */
  shareSendCoupon: function (page) {
    wx.showLoading({
      mask: true,
    });
    if (!page.hideGetCoupon) {
      page.hideGetCoupon = function (e) {
        var url = e.currentTarget.dataset.url || false;
        page.setData({
          get_coupon_list: null,
        });
        if (url) {
          wx.navigateTo({
            url: url,
          });
        }
      };
    }
    this.request({
      url: api.coupon.share_send,
      success: function (res) {
        if (res.code == 200) {
          page.setData({
            get_coupon_list: res.data.list
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  //判断用户是否登录，如果没有登录跳转到allow页面进行授权登录
  getUserAuthorize(){
    
  },
});